<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Events
 *
 * @author tien.nguyen
 */
class Application_Model_Events extends Application_Model_DbTable_Events {

    //put your code here
    public function getEvents($username){
        $select = $this->select()
                ->from('events');
        return $this->fetchAll($select);
    }
    
    public function getEvent($eventId){
        $event = $this->find($eventId)->current();
        return $event;
    
    }
    
    public function convertObject($data){
        $data['eventId'] = isset($data['event_id']) ? $data['event_id'] : null;
        $data['eventName'] = $data['event_name'];
        $data['eventDetail'] = $data['event_detail'];
        $data['eventCategoryId'] = $data['event_category_id'];
        $data['createdDate'] = $data['created_date'] ;
        $data['userId'] = $data['user_id'] ;
        return $data;
    }
   
    private function _convertData($data){
        $data['event_id'] = isset($data['eventId']) ? $data['eventId'] : null;
        $data['event_name'] = $data['eventName'];
        $data['event_detail'] = $data['eventDetail'];
        $data['event_category_id'] = $data['eventCategoryId'];
        $date = new Zend_Date($data['createdDate']);
        $data['created_date'] = $date->toString('yyyy-MM-dd HH:mm:ss');
        $data['user_id'] = $data['userId'] ;
        return $data;
    }

    /**
     * Add event with data by xml
     * @author Tien Nguyne
     * @param string $username
     * @param string $password
     * @param string $data 
     * @return boolean
     */
    public function addEvent($data){
        $data = $this->_convertData($data);
        unset($data['event_id']);
        return $this->createRow($data)->save();
    }
    
    public function listEventCategory(){
        $modelEventCategories = new Application_Model_DbTable_EventCategories();
        return $modelEventCategories->listEventCategories();
    }     
    
    public function editEvent($data){
        $data = $this->_convertData($data);
        $row = $this->find($data['event_id'])->current();
        if($row){
            $row->setFromArray($data);
            return $row->save();
        }
        return FALSE;
    }
    
    public function removeEvent($eventId){
        $event = $this->find($eventId)->current();
        if($event){
            return $this->delete("event_id = '".$eventId."'");
        }
        return false;
    }
    
    /**
     * get list event categories
     * @author Tien Nguyen
     * @param string $username
     */
    public function listEvents($username, $lat, $lng){
        $distance = 100;
        $modelUser = new Application_Model_Users();
        $user = $modelUser->getByUsername($username);
        if($user){
            $distance = (int)$user->distance;
        }
        
        $res = array();
        $listEvents = $this->_getListEvents($username, $distance, $lat, $lng);
        //$listEvents = $this->_validEvents($listEvents,  $distance, $lat, $lng);
//        Zend_Debug::dump($listEvents); die;
        //Zend_Debug::dump($listEvents); die;
        if($listEvents){
            $res  = $listEvents->toArray();
            foreach($res as $k => $item){
                $res[$k] = $this->convertObject($res[$k]);
            }
        }
        return $res;
    }
    
    public function listEventsByUserId($userId, $start = 0, $limit = 10){
        $res = array();
        $select = $this->select()
            ->from('events')
            ->where("events.user_id = ?", $userId)
            ->limit($limit, $start);
            
        $events = $this->fetchAll($select);
        if($events){
            $res  = $events->toArray();
            foreach($res as $k => $item){
                $res[$k] = $this->convertObject($res[$k]);
            }
        }
        return $res;
    }
    
    private function _getListEvents($username, $distance, $lat, $lng){
        $select = $this->select()
                ->from('events')
                ->setIntegrityCheck(false)
                ->join('event_categories', 'event_categories.event_category_id = 
                   events.event_category_id')
                ->where('(((acos(sin(('.$lat.'*pi()/180)) * 
                sin((events.lat*pi()/180))+cos(('.$lat.'*pi()/180)) * 
                cos((events.lat*pi()/180)) * cos((('.$lng.'- events.lng)*pi()
                /180))))*180/pi())*60*1.1515*1.609344) <= ?', $distance)
                ->group(array('events.event_id'))
                ->order(array('events.created_date desc'))
                ->limit(10);

        return $this->fetchAll($select);
    }
    
    private function _validEvents(&$listEvents, $distanceConfig, $lat, $lng){
        $array = array();
        foreach($listEvents as $event){
            $distance = $this->_distance($lat, $lng, $event->lat, $event->lng); 
            if($distance <= $distanceConfig){
//                echo $distance.'     '.$distanceConfig.'<br/>';
                array_push($array, $this->convertObject($event->toArray()));
            }
        }
        return $array;
    }
    
    private function _distance($lat1, $lng1, $lat2, $lng2){
        $distance = 0;
        $url  ='http://maps.googleapis.com/maps/api/distancematrix/json?'.
            'origins='.$lat1.','.$lng1.'|'.$lat2.','.$lng2.'&'.
            'destinations='.$lat1.','.$lng1.'|'.$lat2.','.$lng2.'&'.
            'sensor=false';
        
        $content = file_get_contents($url);
        $json = json_decode($content);
        
        foreach($json->rows as $item){
            
            foreach($item->elements as $needDistance){
                if(isset($needDistance->distance)){
                    $distanceObject = $needDistance->distance;
                    $distance += (int)$distanceObject->value;
                }
            }
        }
        return $distance;
    }

}

?>
